import MD5 from 'js-md5'
import CryptoJS from 'crypto-js'

const common = {}

common.MD5 = MD5;

common.getFormatDate = (date, format, num) => {
	/**
	 * format=1表示获取年月日
	 * format=0表示获取年月日时分秒
	 * num  0：取当前时间，-7：7天前 7：7天后
	 * **/
	let _time = '';
	var now = undefined;
	if (date.trim() !== '') {
		now = new Date(date);
	} else {
		now = new Date();
	}
	now.setDate(now.getDate() + num);
	var year = now.getFullYear();
	var month = now.getMonth() + 1;
	var date = now.getDate();
	var day = now.getDay(); //得到周几
	var hour = now.getHours(); //得到小时
	var minu = now.getMinutes(); //得到分钟
	var sec = now.getSeconds(); //得到秒
	if (format == 1) {
		_time = year + "-" + month + "-" + date
	} else if (format == 2) {
		_time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec
	} else if (format == 3) {
		_time = month + "." + date
	} else if (format == 4) {
		_time = hour + "." + minu
	}
	return _time
}

common.dateFormat = (fmt, date) => {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}

common.timeDiff = (serverDate) => {
	// 计算时间差转为文字表示刚刚，几分钟前
	if (serverDate.trim() == '') {
		return result = "刚刚";
	}
	var minute = 1000 * 60;
	var hour = minute * 60;
	var day = hour * 24;
	var result = '';
	var now = new Date().getTime();
	var dateTimeStamp = new Date(serverDate).getTime();
	var diffValue = now - dateTimeStamp;
	if (diffValue < 0) {
		console.log("时间不对劲,服务器创建时间与当前时间不同步");
		return result = "刚刚";
	}
	var dayC = diffValue / day;
	var hourC = diffValue / hour;
	var minC = diffValue / minute;
	if (parseInt(dayC) > 30) {
		// result = "" + this.$format(dateTimeStamp,"yyyy-MM-dd"); 
		// 超过30天显示当前年月日
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	} else if (parseInt(dayC) > 1) {
		result = "" + parseInt(dayC) + "天前";
	} else if (parseInt(dayC) == 1) {
		result = "昨天";
	} else if (hourC >= 1) {
		result = "" + parseInt(hourC) + "小时前";
	} else if (minC >= 5) {
		result = "" + parseInt(minC) + "分钟前";
	} else
		result = "刚刚";
	return result;
}

common.requestBuilder = function(oldData) { // 请求数据base64加密
	var data = JSON.parse(JSON.stringify(oldData || {})); //保存原始数据
	data = data || {};
	data = common.base64EncodeUTF8(JSON.stringify(data));
	return data;
}

common.responseBuilder = function(oldRes) { // 返回数据base64解密
	var data = JSON.parse(JSON.stringify(oldRes || {})); //保存原始数据
	data = data || {};
	return data;
}

// common.detailBuilder = function(oldRes) {
// 	var data = JSON.stringify(oldRes || {});
// 	data = data || {};
// 	for (var key in data) {
// 		data[key] = Base64.decode(data[key]);
// 	}
// 	return data;
// }

common.imageRequestBuilder = function(oldData) { // 图片信息加密
	var data = JSON.parse(JSON.stringify(oldData || {})); //保存原始数据
	data = data || {};
	console.log(data);
	data = common.base64EncodeUTF8(JSON.stringify(data));
	return data;
}

common.dianji = function(fn) {
	// 处理多次点击
	let that = this;
	if (that.onoff) {
		that.onoff = false;
		fn();
		setTimeout(function() {
			that.onoff = true;
		}, 1500)
	} else {
		//如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
		console.log("请稍后点击")
	}
}

common.checkLogin = function() {
	var userInfo = uni.getStorageSync('userInfo');
	if (userInfo) {
		return true;
	} else {
		uni.reLaunch({
			url: '../login/login'
		})
	}
}
common.checkLogin = function() {
	var userInfo = uni.getStorageSync('userInfo');
	if (userInfo) {
		return true;
	} else {
		uni.reLaunch({
			url: '../login/login'
		})
	}
}

common.getTimeText = function(argument) {
	var timeS = argument;
	var todayT = '';
	var yestodayT = '';
	var timeCha = this.getTimeS(timeS);
	timeS = timeS.slice(-8);
	todayT = new Date().getHours() * 60 * 60 * 1000 + new Date().getMinutes() * 60 * 1000 + new Date().getSeconds() *
		1000;
	yestodayT = todayT + 24 * 60 * 60 * 1000;
	if (timeCha > yestodayT) {
		return argument.slice(5, 11);
	}
	if (timeCha > todayT && timeCha < yestodayT) {
		return timeS.slice(0, 2) > 12 ? '昨天 下午' + (timeS.slice(0, 2) == 12 ? 12 : timeS.slice(0, 2) - 12) + timeS.slice(2,
			5) : '昨天 上午' + timeS.slice(0, 5);
	}
	if (timeCha < todayT) {
		return timeS.slice(0, 2) >= 12 ? '下午' + (timeS.slice(0, 2) == 12 ? 12 : timeS.slice(0, 2) - 12) + timeS.slice(2, 5) :
			'上午' + timeS.slice(0, 5);
	}
}

//时间戳获取
common.getTimeS = function(argument) {
	var timeS = argument;
	timeS = timeS.replace(/[年月]/g, '/').replace(/[日]/, '');
	return new Date().getTime() - new Date(timeS).getTime() - 1000; //有一秒的误差

}

common.base64EncodeUTF8 = function (str) {
	let wordArray = CryptoJS.enc.Utf8.parse(str);
	let base64 = CryptoJS.enc.Base64.stringify(wordArray);
	return base64;
}

common.base64DecodeUTF8 = function (base64) {
	var parsedWordArray = CryptoJS.enc.Base64.parse(base64);
	var parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8);
	return parsedStr;
}

common.showNormalToast = function(text, time=3000) {
	uni.showToast({
		title: text,
		mask: true,
		icon: 'none',
		duration: time
	});
}

common.checkPhone = function(phoneVal) {
	// 验证手机号
	let phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
	if (!(phoneReg.test(phoneVal))) {
		return false;
	} else {
		return true;
	}
}

common.checkVideo = function(str) {
	const videos = ['mp4', 'avi', 'wmv', 'mpg', 'mpeg', 'mov', 'rm', 'ram', 'swf', 'flv']
	return videos.includes(str)
}

common.checkBtn = function(str) {
	const permissionList = ['生产企业']
	return permissionList.includes(str)
}

export default common
